package com.stylefeng.guns.modular.apple.utils;

import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel文件导入导出工具类
 */
public class ExcelUtil {
    /**
     * 读取Excel文件数据内容
     * @param file
     * @return
     * @throws IOException
     */
    public static List<Map<Integer,String>> readExcelData(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();

        if (fileName == null || (!fileName.endsWith(".xls")
                && !fileName.endsWith(".xlsx"))){
            throw new GunsException(BizExceptionEnum.APPLE_EXCEL_FILE_TYPE_ERROR);
        }

        return readExcel(fileName.endsWith(".xls"),file.getInputStream());
    }

    /**
     * 根据文件流读取数据内容
     * @param is2003
     * @param is
     * @return
     * @throws IOException
     */
    private static List<Map<Integer,String>> readExcel(boolean is2003,InputStream is) throws IOException {
        Workbook workbook;
        //判断是否为2003版以前的excel格式
        if (is2003){
            workbook = new HSSFWorkbook(is);
        }else{
            //使用2007版
            workbook = new XSSFWorkbook(is);
        }
        //获取文件第一栏
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null){
            throw new GunsException(BizExceptionEnum.APPLE_EXCEL_SHEET_NOT_EXIST);
        }
        //获取内容行数
        int rowNum = sheet.getLastRowNum();

        List<Map<Integer,String>> excelList = new ArrayList<>();

        for (int i = 1; i <= rowNum; i++) {
            Row row = sheet.getRow(i);
            if (row == null){
                continue;
            }
            Map<Integer,String> excelValues = new HashMap<>();
            int cellNum = row.getLastCellNum();
            for (int j = 0; j < cellNum; j++) {
                if (row.getCell(j).getCellTypeEnum() == CellType._NONE){
                    GunsException gunsException = new GunsException(BizExceptionEnum.APPLE_EXCEL_CELL_NOT_STRING);
                    gunsException.setMessage("导入失败，第"+i+"行内容必须为文本格式");
                    throw gunsException;
                }
                row.getCell(j).setCellType(CellType.STRING);
                if (row.getCell(j).getStringCellValue().isEmpty()){
                    GunsException gunsException = new GunsException(BizExceptionEnum.APPLE_EXCEL_CELL_IS_NULL);
                    gunsException.setMessage("导入失败，第"+i+"行，第"+j+"列,内容为空");
                    throw gunsException;
                }
                excelValues.put(j,row.getCell(j).getStringCellValue());
            }
            excelList.add(excelValues);
        }

        return excelList;
    }


    /**
     * 写入文件并将文件已二进制流的方式返回为调用者
     * @param response
     * @param workbook
     * @param fileName
     */
    public static void writeWorkBook(HttpServletResponse response, HSSFWorkbook workbook, String fileName){
        //清空response
        response.reset();
        //设置response的header
        response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
        try {
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //将excel写入到输入流中
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void setSheetColumnWidth(int colCount,HSSFSheet sheet){
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        for (int i=0;i<colCount;i++){
            sheet.setColumnWidth(i, 20*256);
        }
    }

    /**
     * 设置订单表导出表格的头部信息
     * @param workbook
     * @param sheet
     * @param columns
     */
    public static void setTableHeader(HSSFWorkbook workbook, HSSFSheet sheet, List<String> columns){
        HSSFRow row = sheet.createRow(0);
        setSheetColumnWidth(columns.size(),sheet);

        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);

        HSSFCell cell;
        int len = columns.size();
        for (int i = 0;i<len;i++){
            cell = row.createCell(i);
            cell.setCellValue(columns.get(i));
            cell.setCellStyle(style);
        }
    }

//    public static void main(String[] args) throws IOException {
//        File file = new File("/Users/wg/Downloads/导入AppleId模板.xls");
//        InputStream inputStream = new FileInputStream(file);
//        List<Map<Integer,String>> excelList = readExcel(true,inputStream);
//        System.out.printf(excelList.toString());
//    }

}
